﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebCore.Models;
using Microsoft.EntityFrameworkCore;

namespace WebCore.Controllers
{
    public class ProductController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Add(int? id)
        {
            using (DataContext dbContext = new DataContext())
            {
                product product = new product();
                if (id > 0)
                {
                    product = dbContext.product.FirstOrDefault(t => t.id == id);
                }
                return View(product);
            }
        }

        [HttpPost]
        public JsonResult Add(product model)
        {
            using (DataContext dbContext = new DataContext())
            {
                model.create_date = DateTime.Now;
                if (model.id > 0)
                {
                    var EntityModel = dbContext.Entry(model);
                    dbContext.Set<product>().Attach(model);
                    EntityModel.State = EntityState.Modified;
                    dbContext.SaveChanges();
                    return Json(new { success = true, message = "修改成功" });
                }
                else
                {
                    dbContext.product.Add(model);
                    dbContext.SaveChanges();
                    return Json(new { success = true, message = "添加成功" });
                }
            }
        }

        [HttpPost]
        public JsonResult Delete(int id)
        {
            using (DataContext dbContext = new DataContext())
            {
                var product = dbContext.product.FirstOrDefault(t=>t.id==id);
                dbContext.product.Remove(product);
                dbContext.SaveChanges();
                return Json(new { success = true, message = "删除成功" });
            }
        }
    }
}